package wx

import (
	"xlq-demo/library/config"
	"encoding/json"
	"xlq-demo/library/util"
	"fmt"
	"github.com/tidwall/gjson"
	"strings"
)

//公众号推送


//工作人员小程序 -> 公众号 新增线索
type AppMpClueAddIn struct {
	//小程序openid
	ToUser string `json:"touser"`
	//客户id
	CallId string `json:"callId"`
	//客户手机号
	Phone string `json:"phone"`
	//通话时间
	CallTime string `json:"callTime"`
	//通话时长
	CallDuration string `json:"callDuration"`
}
func AppMpClueAdd(in *AppMpClueAddIn) error {
	reqBody := map[string]interface{}{
		"touser": in.ToUser,
		"mp_template_msg": map[string]interface{}{
			"appid": config.Config.WxMp.AppId,
			"template_id": "IdQz9ElSs79y2lSI2ViUWOzGTzWDESPAmB13ZK7SlL8",
			"url": "http://weixin.qq.com/download",
			"miniprogram": map[string]interface{} {
				"appid": config.Config.WxMine.AppId,
				//江湖写法 通过
				"path": "pages/sound_record/sound?callId="+in.CallId,
				//官方写法 不通过
				//"pagepath": "pages/customer_detail/detail?id="+in.CustomerId,
			},
			"data": map[string]interface{}{
				"first": map[string]string{
					"value": "您与客户的通话记录已上传，请及时建档",
					"color": "#000000",
				},
				"keyword1": map[string]string{
					"value": "未知",
					"color": "#4a4a4a",
				},
				"keyword2": map[string]string{
					"value": in.Phone,
					"color": "#4a4a4a",
				},
				"keyword3": map[string]string{
					"value": in.CallTime,
					"color": "#4a4a4a",
				},
				"keyword4": map[string]string{
					"value": in.CallDuration,
					"color": "#4a4a4a",
				},
				"remark": map[string]string{
					"value": "点击进入“录音详情”，完成客户建档",
					"color": "#ff6c00",
				},
			},
		},
	}

	reqBys,_ := json.Marshal(reqBody)

	accessToken,err := GetWorkerAppAccessToken()
	if err != nil {
		return err
	}
	url := "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token="+accessToken

	//开始请求
	code,resBody,err := util.HttpRequest("POST",url,reqBys,nil)
	fmt.Println(code,string(resBody),err)
	return err
}


//获取公众号素材
type GetNewsOut struct {
	Total int64 `json:"total"`
	Data interface{} `json:"data"`
}
type GetNewsOutData struct {
	MediaId string `json:"mediaId"`
	Title string `json:"title"`
	Digest string `json:"digest"`
	Thumb string `json:"thumb"`
	Url string `json:"url"`
	CreatedTime string `json:"createdTime"`
	UpdatedTime string `json:"updatedTime"`
}
func GetNews(offset,count int) (*GetNewsOut,error) {
	accessToken,err := GetMpAccessToken()
	if err != nil {
		return nil,err
	}

	url := "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + accessToken

	reqBody := []byte(fmt.Sprintf(`{"type":"news","offset":%d,"count":%d}`,offset,count))

	_,resBody,err := util.HttpRequest("POST",url,reqBody,nil)
	if err != nil {
		fmt.Println("获取素材报错",err)
		return nil,err
	}

	//读取内容
	resObj := gjson.ParseBytes(resBody)

	//判断是否存在报错
	if resObj.Get("errcode").Exists() {
		fmt.Println("获取素材报错",string(resBody))
		return nil,fmt.Errorf("获取素材报错: %s",resObj.Get("errmsg").String())
	}

	totalCount := resObj.Get("total_count").Int()
	itemCount := resObj.Get("item_count").Int()

	items := make([]GetNewsOutData,itemCount)
	for key,val := range resObj.Get("item").Array() {
		news := val.Get("content").Get("news_item").Array()[0]

		//获取封面图二进制
		thumburl := news.Get("thumb_url").String()
		//_,thumbBys,err := comm.HttpRequest("GET",thumburl,nil,nil)
		/*thumb := ""
		if err != nil {
			fmt.Println("获取素材封面失败：",err,thumburl)
		} else {
			thumb = strings.Replace(thumburl,"http://mmbiz.qpic.cn","http://api.dudutalk.com/wx",1)
			//thumb = base64.StdEncoding.EncodeToString(thumbBys)
		}*/
		thumb := strings.Replace(thumburl,"http://mmbiz.qpic.cn","http://api.dudutalk.com/wx",1)

		items[key] = GetNewsOutData{
			MediaId: val.Get("media_id").String(),
			Title: news.Get("title").String(),
			Digest: news.Get("digest").String(),
			Thumb: thumb,
			Url: news.Get("url").String(),
			CreatedTime: util.TimeFormat(val.Get("content").Get("create_time").Int(),3),
			UpdatedTime: util.TimeFormat(val.Get("content").Get("update_time").Int(),3),
		}
	}
	out := &GetNewsOut{
		Total: totalCount,
		Data: items,
	}
	return out,nil
}

